package com.example.service.impl;

import com.example.config.file.LocalFileProperties;
import com.example.service.FileService;
import org.apache.commons.io.FilenameUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Service
@Transactional
public class FileServiceImpl implements FileService {
    @Resource
    private LocalFileProperties localFileProperties;

    @Value("#{'${file.allowed-extensions}'.split(',')}")
    private List<String> allowedExtensions;

    private static final Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    /**
     * 文件上传
     * @param file 文件上传对象
     * @param module 问价名称
     * @return
     */
    @Override
    public String upload(MultipartFile file, String module) {
        logger.info("开始上传文件，模块：{}, 原始文件名：{}", module, file.getOriginalFilename());
        try {
            // 获取原始文件名
            String originalFilename = file.getOriginalFilename();
            String extension = FilenameUtils.getExtension(originalFilename);
            String newFileName = UUID.randomUUID() + "." + extension;

            // 构建日期路径 yyyy/MM/dd
            String datePath = new DateTime().toString("yyyy/MM/dd");

            // 构建完整路径
            String fullPath = localFileProperties.getUploadDir() + module + "/" + datePath;
            File dir = new File(fullPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 写入文件
            File dest = new File(fullPath + "/" + newFileName);
            file.transferTo(dest);

            // 返回访问 URL
            return localFileProperties.getAccessUrl() + module + "/" + datePath + "/" + newFileName;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 删除文件
     * @param url
     */
    @Override
    public void deleteFile(String url) {
        String relativePath = url.replace(localFileProperties.getAccessUrl(), "");
        File file = new File(localFileProperties.getUploadDir() + relativePath);
        if (file.exists()) {
            file.delete();
        }
    }
}
